<?php

namespace App\Services\Tools;


define('SM_API_TEXT_HOST', 'http://api-text-sh.fengkongcloud.com');
define('SM_API_IMG_HOST', 'http://api-img-sh.fengkongcloud.com');
define('SM_API_AUDIO_HOST', 'http://api-audio-sh.fengkongcloud.com');
define('SM_API_AUDIO_STREAM_HOST', 'http://api-audiostream-sh.fengkongcloud.com');
define('SM_API_FENG_KONG_URL', 'http://api-skynet-bj.fengkongcloud.com/v4/event');  // 数美风控地址

define('SM_ACCESSKEY', '9IKAKOYJqDUw5QG30Mnw');
define('TEXT_URI', '/v2/saas/anti_fraud/text');
define('IMG_URI', '/v2/saas/anti_fraud/img');
define('AUDIO_URI', '/v2/saas/anti_fraud/audio');
define('AUDIO_STREAM_URI', '/v2/saas/anti_fraud/audiostream');

class ShuMeiService
{
    public $riskLevel = '';
    public function getRiskLevel() {
        return $this->riskLevel;
    }

    public function checkTextApi($text, $user_id = 0, $ext = [],$maxCurlTime=5){
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'SOCIAL';

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;       // 设置tokenId, 由客户提供
        $dataParams['text'] = $text;                      // 设置文本内容

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_TEXT_HOST.TEXT_URI; // 设置请求url地址

        $response = $this->Post($url, $postData,$maxCurlTime); // 发起接口请求
        $resJson = json_decode($response, true);
        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
        if ($resJson["code"] == 1100) {
            return [
                'code' => 200,
                'originData' => $resJson,
                'msg' => '请求成功',
            ];
        }
        return [
            'code' => 400,
            'originData' => $resJson,
            'msg' => $resJson['message']??'请求失败',
        ];
    }

    //过滤文本
    public function checkText($text, $user_id = 0, $ext = [],$maxCurlTime=5)
    {

        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'SOCIAL';

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;       // 设置tokenId, 由客户提供
        $dataParams['text'] = $text;                      // 设置文本内容

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_TEXT_HOST.TEXT_URI; // 设置请求url地址

        $response = $this->Post($url, $postData,$maxCurlTime); // 发起接口请求
        $resJson = json_decode($response, true);

        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
        if ($resJson["code"] == 1100) {
            $this->riskLevel = $resJson["riskLevel"];
            if ($resJson["riskLevel"] == "REJECT") {
                return true;
            }
        }

        return false;
    }

    //过滤主播私信渠道
    public function checkSociatyText($text, $user_id = 0, $ext = [])
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'SOCIAL';

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;       // 设置tokenId, 由客户提供
        $dataParams['text'] = $text;                      // 设置文本内容

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_TEXT_HOST.TEXT_URI; // 设置请求url地址

        $response = $this->Post($url, $postData); // 发起接口请求
        $resJson = json_decode($response, true);

        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
        if ($resJson["code"] == 1100) {
            if ($resJson["riskLevel"] == "REJECT") {
                return true;
            }
        }

        return false;
    }

    public function getExtData($ext = [])
    {
        $dataParams['ip'] = HelperService::get_real_ip();

        if (isset($ext['channel'])) {
            $dataParams['channel'] = $ext['channel'];
        }
        if (isset($ext['nickname'])) {
            $dataParams['nickname'] = $ext['nickname'];
        }
        if (isset($ext['receiveTokenId'])) {
            $dataParams['receiveTokenId'] = $ext['receiveTokenId'];
        }
        if (isset($ext['room_id'])) {
            $dataParams['room_id'] = $ext['room_id'];
        }
        if (isset($ext['room'])) {
            $dataParams['room'] = $ext['room'];
        }

        return $dataParams;
    }
    //语音回调
    public function audioCallBack(){
        $response = file_get_contents('php://input');
        $resJson = json_decode($response, true);
        Helper::recordLog($resJson);
        if ($resJson["code"] == 1100 && $resJson["riskLevel"] == "REJECT") {
            $scene = $resJson['callbackParam']['scene'] ?? 0;
            $method = 'action_' . $scene;
            if (method_exists($this, $method)) {
                $this->$method($resJson);
            }
        }
        return true;
    }

    //处理私聊语音违规
    private function action_message($resJson) {
        $user_id = $this->getUserId($resJson['btId']);
        (new UserNews())->sendUserNews($user_id, '涉嫌违规', '您的言论涉嫌违规，平台将对你做出系统通报。');
    }

    //处理私聊语音违规
    private function action_intro_voice($resJson) {
        $user_id = $this->getUserId($resJson['btId']);
        //@todo
    }

    private function getUserId($btId) {
        $btId_array = explode('-', $btId);
        return $btId_array[0] ?? 0;
    }

    //过滤图片
    public function checkImage($image, $user_id = 0, $ext = [])
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'POLITICS_PORN_AD_BEHAVIOR';

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;       // 设置tokenId, 由客户提供
        $dataParams['img'] = $image;                      // 设置图片参数，这里也可以提供图片的 http 后者 https 链接

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_IMG_HOST.IMG_URI; // 设置请求url地址

        $response = $this->Post($url, $postData); // 发起接口请求
        $resJson = json_decode($response, true);
        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
        //todo 正式返回array(4) {
//        ["code"]=>
//  int(1902)
//  ["message"]=>
//  string(57) "参数不合法(Server get request error,statuscode: 404)"
//    ["requestId"]=>
//  string(32) "ea64e7eb0ca125751a776e2bc78f1256"
//    ["taskId"]=>
//  string(35) "a9628785-e0dc6ecc-ae170686-65788128"
//}

        if ($resJson["code"] == 1100) {
            if ($resJson["riskLevel"] == "REJECT") {
                return true;
            }
        }
        return false;
    }

    //过滤音频 异步回调返回结果
    public function checkAudio($audio, $user_id = 0, $ext = [])
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'POLITICAL_PORN_MOAN';
        $postData['btId'] = $ext['btId'];
        $appUrl = \EasySwoole\Component\Di::getInstance()->get('server_config');
        $appUrl = trim($appUrl['LOCAL']['HOST'],'/');
        $postData['callback'] = $appUrl."/api/shumei/audio";
        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;           // 设置tokenId, 由客户提供
        $dataParams['url'] = $audio;                          // 设置图片参数，这里也可以提供图片的 http 后者 https 链接

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_AUDIO_HOST.AUDIO_URI; // 设置请求url地址

        $this->Post($url, $postData); // 发起接口请求
    }

    //过滤音频 异步回调返回结果
    public function checkAudioStream($audio, $user_id = 0, $ext = [])
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'AD_PORN_POLITICAL';
        $postData['btId'] = $ext['btId'];
        $postData['callback'] = U('Api/ShuMei/audioStream', '', true, true);

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;           // 设置tokenId, 由客户提供
        $dataParams['url'] = $audio;                          // 设置图片参数，这里也可以提供图片的 http 后者 https 链接
        $dataParams['streamType'] = 'ZEGO';
        $dataParams['zegoParam'] = 'ZEGO';
        $dataParams['audioName'] = 'ZEGO';
        $dataParams['room'] = 'ZEGO';

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_AUDIO_HOST.AUDIO_URI; // 设置请求url地址

        $this->Post($url, $postData); // 发起接口请求
    }

    //关闭音频流过滤
    public function audioStreamFinish($audio, $user_id = 0, $ext = [])
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['type'] = 'AD_PORN_POLITICAL';
        $postData['btId'] = $ext['btId'];
        $postData['callback'] = U('Api/ShuMei/audioStream', '', true, true);

        $dataParams = [];
        $dataParams['tokenId'] = (string) $user_id;           // 设置tokenId, 由客户提供
        $dataParams['url'] = $audio;                          // 设置图片参数，这里也可以提供图片的 http 后者 https 链接
        $dataParams['streamType'] = 'ZEGO';
        $dataParams['zegoParam'] = 'ZEGO';
        $dataParams['audioName'] = 'ZEGO';
        $dataParams['room'] = 'ZEGO';

        $postData['data'] = array_merge($dataParams, $this->getExtData($ext));

        $url = SM_API_AUDIO_HOST.AUDIO_URI; // 设置请求url地址

        $this->Post($url, $postData); // 发起接口请求
    }

    public function Get($url)
    {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);

        //返回结果
        return $output;
    }

    public function Post($url, $postData,$maxCurlTime=5)
    {
        $data_string = json_encode($postData);
//        echo "请求参数:" . $data_string . PHP_EOL;
        $ch = curl_init();
        // 设置超时时间
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $maxCurlTime);
        curl_setopt($ch, CURLOPT_TIMEOUT, $maxCurlTime);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER,
            ['Content-Type: application/json; charset=utf-8', 'Content-Length: '.strlen($data_string)]);
        $output = curl_exec($ch);
        curl_close($ch);

        //返回结果
        return $output;
    }

    public function checkRegister($userId, $phone, $registerIp, $registerTime, $clientType, $appVersion, $deviceId = '')
    {
        $postData['accessKey'] = SM_ACCESSKEY;
        $postData['appid'] = 'default';
        $postData['eventId'] = 'register';


        $dataParams = [];
        $dataParams['tokenId'] = (string) $userId;       // 设置tokenId, 由客户提供
        $dataParams['isTokenSeperate'] = 0; // 是否区分账号体系同公司不同 app 接入，未统一账号体系，不同 app，不同用户出现相同账号，需要区分账号体系，0，不区分，1，区分。
        $dataParams['ip'] = $registerIp;
        if(!empty($deviceId)){
            $dataParams['deviceId'] = (string)$deviceId;
        }
        $dataParams['timestamp'] = $registerTime;
        $dataParams['os'] = $clientType;
        $dataParams['appVersion'] = $appVersion;
        $dataParams['phone'] = md5($phone);
        $dataParams['countryCode'] = "0086";


        $postData['data'] = $dataParams;

        $url = SM_API_FENG_KONG_URL; // 设置请求url地址

        $response = $this->Post($url, $postData); // 发起接口请求
        $resJson = json_decode($response, true);

        /**
         * 接口会返回code， code=1100 时说明请求成功，根据不同的 riskLevel 风险级别进行业务处理
         * 当 code!=1100 时，如果是 1902 错误，需要检查参数配置
         * 其余情况需要根据错误码进行重试或者其它异常处理
         */
//        print_r($resJson);
        if ($resJson["code"] == 1100) {
            $this->riskLevel = $resJson["riskLevel"];
            if ($resJson["riskLevel"] == "REJECT") {
//                return $resJson
                return $resJson['detail']['description'] ?? json_encode($resJson['detail']);
//                return true;
            }
        }

        return false;
    }
}
